/**
 * 树形目录管理模块
 */
class TreeManager {
    constructor() {
        this.tree = null;
        this.layer = null;
        this.currentConfig = null;
        this.connectionId = null;
        this.currentPath = "";
        this.isLoading = false;

        this.clickTimer = null;
        this.clickDelay = 300; // 300ms内的第二次点击视为双击
        
        this.init();
    }

    init() {
        // 等待layui加载完成
        layui.use(['tree', 'layer'], (tree, layer) => {
            this.tree = tree;
            this.layer = layer;
            this.currentPath = document.getElementById('treeCurrentPath').textContent;
            this.bindButtons();

        });
    }

    // 绑定按钮
    bindButtons() {
        document.getElementById('refreshTreeBtn').addEventListener('click', () => {
            this.loadTreeWithPath(this.currentPath);
        });
        document.getElementById('treeCurrentPath').addEventListener('click', (e) => {
            this.layer.prompt({
                title: '请输入路径',
                value: e.target.textContent,
                formType: 0,
                maxlength: 255,
                minlength: 1,
                success: function(layero, index) {
                    // 修改整个弹窗宽度
                    layero.css('width', '600px');
                    // 修改输入框宽度
                    layero.find('.layui-layer-input').css('width', '500px');
                    // 弹开位置
                    layero.css('top', '300px');
                    // 弹开位置
                    layero.css('left', '400px');

                }
            }, (value, index, elem) =>{
                if(value === '') return elem.focus();

                // 打开文件
                this.loadTreeWithPath(value);

                // 关闭 prompt
                layer.close(index);
            });            
        })
    }


    // 加载目录树
    loadTree() {
        const config = window.getConfig();
        if (!config || !config.host) {
            // this.layer.msg('请先输入配置');
            return;
        }
        
        this.showLoading(true);
        document.getElementById('directoryTree').innerHTML = '';
        // this.showStatus('正在加载目录: ' + config.remote_path);
        window.showStatusMessage('正在加载目录: ' + config.remotePath, 'info');

        const hostKey = `${config.name}|${config.host}:${config.port}|${config.username}`;
        const commandConfig = {
            cmd_event: "tree",
            params: [config.remotePath, config.maxDepth],
            hosts_key: [hostKey]
        };
        window.SocketClient.sendCommand(commandConfig);
    }

    loadTreeWithPath(path){
        const config = window.getConfig();
        if (!config || !config.host) {
            // this.layer.msg('请先输入配置');
            return;
        }
        
        this.showLoading(true);
        document.getElementById('directoryTree').innerHTML = '';
        // this.showStatus('正在加载目录: ' + config.remote_path);
        window.showStatusMessage('正在加载目录: ' + config.remotePath, 'info');

        const hostKey = `${config.name}|${config.host}:${config.port}|${config.username}`;
        const commandConfig = {
            cmd_event: "tree",
            params: [path, config.maxDepth],
            hosts_key: [hostKey]
        };
        window.SocketClient.sendCommand(commandConfig);
    }


    // 处理事件结果
    handleEventResult(data) {
        this.showLoading(false);
        
        if (data.success && data.cmd_event === 'tree') {
            this.renderTree(data.data[0].content);
            this.currentPath = data.data[0].base_path;
            document.getElementById('treeCurrentPath').textContent = this.currentPath;
            window.showStatusMessage(data.msg, 'success');
        } else {
            window.showStatusMessage(data.msg, 'error');
        }
    }

    // 渲染树形结构
    renderTree(treeData) {
        if (!this.tree) return;

        this.tree.render({
            elem: '#directoryTree',
            data: treeData,
            showCheckbox: false,
            id: 'directoryTreeId',
            isJump: false,
            accordion: true,
            click: (obj) => {
                console.log('树状图选中:', obj.data.field);
                // 处理点击事件只对无childern的节点生效
                if (obj.data.children.length>0) {
                    return;
                }
                if (this.clickTimer) {
                    // 双击
                    clearTimeout(this.clickTimer);
                    this.clickTimer = null;
                    console.log('双击:', obj.data.field);

                    window.EditorManager.loadFile(obj.data.field);
                } else {
                    // 可能是单击，等待确认
                    this.clickTimer = setTimeout(() => {
                        // 确认是单击
                        this.clickTimer = null;
                        console.log('单击:', obj.data.field);
                        // handleSingleClick(obj);
                    }, this.clickDelay);

                }

                // 更新当前路径显示
                // document.getElementById('currentPathDisplay').textContent = obj.data.field;
            }

        });
        
    }

    // 显示加载状态
    showLoading(show) {
        const loading = document.getElementById('loading-tree');
        this.isLoading = show;
        loading.style.display = show ? 'block' : 'none';
    }

}

// 创建全局TreeManager实例
window.TreeManager = new TreeManager();